package com.daisuxia.task;

import static com.daisuxia.web.pojo.BorrowOrder.STATUS_BFHK;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_HKZ;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_YHK;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_YHZ;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_YQYHK;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_YYQ;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.ReportRepayment;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IRepaymentService;
import com.daisuxia.web.service.IReportRepaymentService;

import redis.clients.jedis.JedisCluster;

/**
 * @author lgy 2017-10-09 11:20:20
 * 每日还款、逾期报表
 */

public class RepaymentReportTaskService {
	private static Logger logger = LoggerFactory.getLogger(RepaymentReportTaskService.class);
	@Autowired
	JedisCluster jedisCluster;
	@Autowired
	private IRepaymentService repaymentService;
	@Autowired
	private IReportRepaymentService reportRepaymentService;



	public void reportRepayment(String firstRepaymentTime, boolean showOverdute) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		logger.error("每日还款、逾期报表任务开始---------->reportRepayment start " + firstRepaymentTime + " " + showOverdute);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("firstRepaymentTime", firstRepaymentTime);
		List<Repayment> repayments = repaymentService.findByRepaymentReport(params);

		// 逾期、正常还款、部分还款
		Long expireAmount = 0L; // 到期金额
		Long expireCount = (long) repayments.size(); // 总数量
		Long overdueAmount = 0L; // 新增逾期金额
		Long overdueCount = 0L; // 逾期数量
		Long overdueCountSeven = 0L; // 逾期7天数量
		Long overdueAmountSeven = 0L; // 逾期7天金额
		Long overdueCountFourteen = 0L; // 逾期14天数量
		Long overdueAmountFourteen = 0L; // 逾期14天金额
		Long countSeven = 0L; // 7天数量
		Long countFourteen = 0L; // 14天数量
		Long amountSeven = 0L; // 7天金额
		Long amountFourteen = 0L; // 14天金额
		Long repayCount = 0L; // 今日还款数量
		Long repayAmount = 0L; // 今日还款金额
		Long oldOverdueCount = 0L; // 今日老用户逾期数量
		Long oldOverdueAmount = 0L; // 今日老用户逾期金额
		Long newOverdueCount = 0L; // 今日新用户逾期数量
		Long newOverdueAmount = 0L; // 今日新用户逾期金额
		Long oldRepayCount = 0L; // 今日老用户还款数量
		Long oldRepayAmount = 0L; // 今日老用户还款金额
		Long newRepayCount = 0L; // 今日新用户还款数量
		Long newRepayAmount = 0L; // 今日新用户还款金额
		Long newExpireAmount = 0L; // 今日新用户到期金额
		Long newExpireCount = 0L; // 今日新用户到期数量
		Long oldExpireAmount = 0L; // 今日老用户到期金额
		Long oldExpireCount = 0L; // 今日老用户到期数量

		for (Repayment re : repayments) {
			int moneyAmount = (int) (re.getRepaymentPrincipal() + re.getRepaymentInterest());
			int status = re.getStatus();
			String repaymentTime = dateFormat.format(re.getRepaymentTime());
			String firstRepayment = dateFormat.format(re.getFirstRepaymentTime());
			if (status == STATUS_YHK || !repaymentTime.equals(firstRepayment)) {
				// 新增还款金额 还款数量
				repayAmount += moneyAmount;
				repayCount++;
				// 新旧用户已还数量
				if (User.CUSTOMER_OLD.equals(String.valueOf(re.getCustomerType()))) {
					oldRepayCount++;
					oldRepayAmount += moneyAmount;
				} else {
					newRepayCount++;
					newRepayAmount += moneyAmount;
				}
			} else {
				// 新增逾期金额 逾期数量
				overdueAmount += moneyAmount;
				overdueCount++;
				// 新旧用户逾期数量 逾期金额
				if (User.CUSTOMER_OLD.equals(String.valueOf(re.getCustomerType()))) {
					oldOverdueCount++;
					oldOverdueAmount += moneyAmount;
				} else {
					newOverdueCount++;
					newOverdueAmount += moneyAmount;
				}
				// 7天14天逾期数量
				if (re.getLoanTerm() == 7) {
					overdueCountSeven++;
					overdueAmountSeven += moneyAmount;
				} else {
					overdueCountFourteen++;
					overdueAmountFourteen += moneyAmount;
				}
			}
			// 计算总数量
			if (re.getLoanTerm() == 7) {
				countSeven++;
				amountSeven += moneyAmount;
			} else {
				countFourteen++;
				amountFourteen += moneyAmount;
			}
			// 到期金额
			expireAmount += moneyAmount;
			// 新老用户到期金额
			if (User.CUSTOMER_OLD.equals(String.valueOf(re.getCustomerType()))) {
				oldExpireAmount += moneyAmount;
				oldExpireCount++;
			} else {
				newExpireAmount += moneyAmount;
				newExpireCount++;
			}
		}

		List<Map<String, Object>> renewals = reportRepaymentService.findRenewalByRepaymentReport(params);
		expireCount += renewals.size();
		for (Map<String, Object> renewal : renewals) {
			String repaymentTime = dateFormat.format(renewal.get("repaymentTime"));
			String repaymentTimeRe = dateFormat.format(renewal.get("repaymentTimeRe"));
			int moneyAmount = Integer.parseInt(renewal.get("moneyAmount").toString());
			int status = Integer.parseInt(renewal.get("status").toString());
			int loanTerm = Integer.parseInt(renewal.get("loanTerm").toString());
			if (status == STATUS_YHK || !repaymentTime.equals(repaymentTimeRe)) {
				// 新增还款金额 还款数量
				repayAmount += moneyAmount;
				repayCount++;
				// 旧用户已还数量
				oldRepayCount++;
				oldRepayAmount += moneyAmount;
			} else {
				// 新增逾期金额 逾期数量
				overdueAmount += moneyAmount;
				overdueCount++;
				// 旧用户逾期数量 逾期金额
				oldOverdueCount++;
				oldOverdueAmount += moneyAmount;
				// 7天14天逾期数量
				if (loanTerm == 7) {
					overdueCountSeven++;
					overdueAmountSeven += moneyAmount;
				} else {
					overdueCountFourteen++;
					overdueAmountFourteen += moneyAmount;
				}
			}
			// 计算总数量
			if (loanTerm == 7) {
				countSeven++;
				amountSeven += moneyAmount;
			} else {
				countFourteen++;
				amountFourteen += moneyAmount;
			}
			// 到期金额
			expireAmount += moneyAmount;
			// 老用户到期金额
			oldExpireAmount += moneyAmount;
			oldExpireCount++;
		}

		ReportRepayment report = new ReportRepayment();
		report.setReportDate(firstRepaymentTime);
		if (expireCount > 0) {
			if (showOverdute) {
				report.setOverdueRate(overdueCount * 10000 / expireCount);
				if (countSeven > 0) {
					report.setOverdueRateSeven(overdueCountSeven * 10000 / countSeven);
				}
				if (countFourteen > 0) {
					report.setOverdueRateFourteen(overdueCountFourteen * 10000 / countFourteen);
				}
				if (oldExpireCount > 0) {
					report.setOverdueRateOld(oldOverdueCount * 10000 / oldExpireCount);
				}
				if (newExpireCount > 0) {
					report.setOverdueRateNew(newOverdueCount * 10000 / newExpireCount);
				}

				report.setOverdueAmount(overdueAmount);
				report.setOverdueRateAmount(overdueAmount * 10000 / expireAmount);
				if (amountSeven > 0) {
					report.setOverdueRateSevenAmount(overdueAmountSeven * 10000 / amountSeven);
				}
				if (amountFourteen > 0) {
					report.setOverdueRateFourteenAmount(overdueAmountFourteen * 10000 / amountFourteen);
				}
				report.setOverdueAmountOld(oldOverdueAmount);
				report.setOverdueAmountNew(newOverdueAmount);
				if (oldExpireAmount > 0) {
					report.setOverdueRateOldAmount(oldOverdueAmount * 10000 / oldExpireAmount);
				}
				if (newExpireAmount > 0) {
					report.setOverdueRateNewAmount(newOverdueAmount * 10000 / newExpireAmount);
				}
			}
			report.setRepayRate(repayCount * 10000 / expireCount);

			if (oldExpireCount > 0) {
				report.setRepayRateOld(oldRepayCount * 10000 / oldExpireCount);
			}
			if (newExpireCount > 0) {
				report.setRepayRateNew(newRepayCount * 10000 / newExpireCount);
			}

			report.setExpireAmount(expireAmount);

			report.setExpireAmountOld(oldExpireAmount);
			report.setExpireAmountNew(newExpireAmount);

			report.setRepayRateAmount(repayAmount * 10000 / expireAmount);
			if (oldExpireAmount > 0) {
				report.setRepayRateOldAmount(oldRepayAmount * 10000 / oldExpireAmount);
			}
			if (newExpireAmount > 0) {
				report.setRepayRateNewAmount(newRepayAmount * 10000 / newExpireAmount);
			}
		}

		params.clear();
		Integer[] statuses = new Integer[] { STATUS_HKZ, STATUS_BFHK, STATUS_YHZ, STATUS_YYQ, STATUS_YHK,
				STATUS_YQYHK };
		params.put("statuses", statuses);
		params.put("firstRepaymentTimeEnd", firstRepaymentTime);
		// repayments = repaymentService.findByRepaymentReport(params);

		Long allCount = 0L; // 总借款数量
		Long allAmount = 0L; // 总借款金额
		Long allBorrowCount = 0L; // 当前借款数量
		Long allBorrowAmount = 0L; // 当前借款金额
		Long allRepayCount = 0L; // 当前还款数量
		Long allRepayAmount = 0L; // 当前还款金额
		Long allOverdueCount = 0L; // 当前逾期数量
		Long allOverdueAmount = 0L; // 当前逾期金额
		Long overdueS1Count = 0L; // 当前逾期S1数量
		Long overdueS1Amount = 0L; // 当前逾期S1金额
		Long overdueS2Count = 0L; // 当前逾期S2数量
		Long overdueS2Amount = 0L; // 当前逾期S2金额
		Long overdueS3Count = 0L; // 当前逾期S3数量
		Long overdueS3Amount = 0L; // 当前逾期S3金额
		Long overdueM3Count = 0L; // 当前逾期M3数量
		Long overdueM3Amount = 0L; // 当前逾期M3金额

		// 总借款数量、金额
		Map<String, Object> map = reportRepaymentService.findAllByReport(firstRepaymentTime);
		allCount += (Long) map.get("countAll");
		if(map.get("amountAll")!=null) {
		    allAmount += ((BigDecimal) map.get("amountAll")).longValue();
		}
		map = reportRepaymentService.findAllRenewalByReport(firstRepaymentTime);
		allCount += (Long) map.get("countAll");
		if(map.get("amountAll")!=null) {
			allAmount += ((BigDecimal) map.get("amountAll")).longValue();
		}
		// 当前借款数量、金额
		map = reportRepaymentService.findAllBorrowByReport(firstRepaymentTime);
		allBorrowCount += (Long) map.get("countAll");
		if(map.get("amountAll")!=null) {
			allBorrowAmount += ((BigDecimal) map.get("amountAll")).longValue();
		}
		map = reportRepaymentService.findAllRenewalBorrowByReport(firstRepaymentTime);
		allBorrowCount += (Long) map.get("countAll");
		if(map.get("amountAll")!=null) {
			allBorrowAmount += ((BigDecimal) map.get("amountAll")).longValue();
		}
		// 当前还款数量、金额
		map = reportRepaymentService.findAllRepayByReport(firstRepaymentTime);
		allRepayCount += (Long) map.get("countAll");
		if(map.get("amountAll")!=null) {
			allRepayAmount += ((BigDecimal) map.get("amountAll")).longValue();
		}
		map = reportRepaymentService.findAllRenewalRepayByReport(firstRepaymentTime);
		allRepayCount += (Long) map.get("countAll");
		if(map.get("amountAll")!=null) {
			allRepayAmount += ((BigDecimal) map.get("amountAll")).longValue(); 
		} 
		// 当前逾期数量、金额
		map = reportRepaymentService.findAllOverdueByReport(firstRepaymentTime);
		allOverdueCount += (Long) map.get("countAll");
		if(map.get("amountAll")!=null) {
			allOverdueAmount += ((BigDecimal) map.get("amountAll")).longValue();
	    }
		// S1S2S3数量、金额
		params.clear();
		params.put("reportTime", firstRepaymentTime);
		params.put("reportTimeOneHour", firstRepaymentTime + " 01:00:00");
		List<Map<String, Object>> list = reportRepaymentService.findOverdueRateSByReport(params);

		for (Map<String, Object> temp : list) {
			long lateDay = Long.parseLong(temp.get("lateDay").toString());
			long countAll = (Long) temp.get("countAll");
			long amountAll = ((BigDecimal) temp.get("amountAll")).longValue();
			if (lateDay > 0 && lateDay <= 10) {
				overdueS1Count += countAll;
				overdueS1Amount += amountAll;
			} else if (lateDay > 10 && lateDay <= 30) {
				overdueS2Count += countAll;
				overdueS2Amount += amountAll;
			} else if (lateDay > 30 && lateDay <= 60) {
				overdueS3Count += countAll;
				overdueS3Amount += amountAll;
			} else if (lateDay > 60 && lateDay <= 90) {
				overdueM3Count += countAll;
				overdueM3Amount += amountAll;
			}
		}

		/*
		 * for (Repayment re : repayments) { int status = re.getStatus(); int
		 * moneyAmount = (int) (re.getRepaymentPrincipal() + re.getRepaymentInterest());
		 * allCount++; allAmount += moneyAmount; // 还款完成金额、数量 if (STATUS_YHK == status
		 * || STATUS_YQYHK == status) { allRepayCount++; allRepayAmount += moneyAmount;
		 * } else { // 当前借款金额、数量 allBorrowCount++; allBorrowAmount += moneyAmount; //
		 * 逾期中数量、金额 if (STATUS_YYQ == status) { allOverdueCount++; allOverdueAmount +=
		 * moneyAmount;
		 *
		 * if (re.getLateDay() > 0 && re.getLateDay() <= 10) { overdueS1Count++;
		 * overdueS1Amount += moneyAmount; } else if (re.getLateDay() > 10 &&
		 * re.getLateDay() <= 30) { overdueS2Count++; overdueS2Amount += moneyAmount; }
		 * else if (re.getLateDay() > 30 && re.getLateDay() <= 60) { overdueS3Count++;
		 * overdueS3Amount += moneyAmount; } } } }
		 *
		 * renewals = reportRepaymentService.findRenewalByRepaymentReport(params); for
		 * (Map<String, Object> renewal : renewals) { int moneyAmount =
		 * Integer.parseInt(renewal.get("moneyAmount").toString()); int status =
		 * Integer.parseInt(renewal.get("status").toString()); int lateDay =
		 * Integer.parseInt(renewal.get("lateDay").toString()); allCount++; allAmount +=
		 * moneyAmount; // 还款完成金额、数量 if (STATUS_YHK == status || STATUS_YQYHK == status)
		 * { allRepayCount++; allRepayAmount += moneyAmount; } else { // 当前借款金额、数量
		 * allBorrowCount++; allBorrowAmount += moneyAmount; // 逾期中数量、金额 if (STATUS_YYQ
		 * == status) { allOverdueCount++; allOverdueAmount += moneyAmount;
		 *
		 * if (lateDay > 0 && lateDay <= 10) { overdueS1Count++; overdueS1Amount +=
		 * moneyAmount; } else if (lateDay > 10 && lateDay <= 30) { overdueS2Count++;
		 * overdueS2Amount += moneyAmount; } else if (lateDay > 30 && lateDay <= 60) {
		 * overdueS3Count++; overdueS3Amount += moneyAmount; } } } }
		 */

		if (allCount > 0) {
			report.setAllBorrowCount(allBorrowCount);
			report.setAllBorrowAmount(allBorrowAmount);
			report.setAllRepayCount(allRepayCount);
			report.setAllRepayAmount(allRepayAmount);
			report.setAllOverdueCount(allOverdueCount);
			report.setAllOverdueAmount(allOverdueAmount);
			report.setOverdueRateS1Count(overdueS1Count * 10000 / allCount);
			report.setOverdueRateS1Amount(overdueS1Amount * 10000 / allAmount);
			report.setOverdueRateS2Count(overdueS2Count * 10000 / allCount);
			report.setOverdueRateS2Amount(overdueS2Amount * 10000 / allAmount);
			report.setOverdueRateS3Count(overdueS3Count * 10000 / allCount);
			report.setOverdueRateS3Amount(overdueS3Amount * 10000 / allAmount);
			report.setOverdueRateM3Count(overdueM3Count * 10000 / allCount);
			report.setOverdueRateM3Amount(overdueM3Amount * 10000 / allAmount);
		}

		Integer id = reportRepaymentService.findIdByDate(report.getReportDate());
		if (null == id) {
			reportRepaymentService.insertSelective(report);
		} else {
			report.setId(id);
			reportRepaymentService.updateByPrimaryKeySelective(report);
		}

		logger.error("每日还款、逾期报表任务结束---------->reportRepayment end " + firstRepaymentTime);
	}

	/**
	 * 每日还款、逾期报表 中午12点
	 */
	public void reportRepayment12() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String firstRepaymentTime;
		Calendar now = Calendar.getInstance();
		now.add(Calendar.DAY_OF_YEAR, -1);
		firstRepaymentTime = dateFormat.format(now.getTime());
		// 12点后的定时 更新前一日数据 （带逾期信息）
		reportRepayment(firstRepaymentTime, true);
	}
	/**
	 * 每日还款、逾期报表 每两个小时
	 */
	public void reportRepaymentE2() {
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String firstRepaymentTime;
		Calendar now = Calendar.getInstance();
		// 12点后 只更新当日 （不带逾期信息）
		if (now.get(Calendar.HOUR_OF_DAY) >= 4) {
			firstRepaymentTime = dateFormat.format(now.getTime());
			reportRepayment(firstRepaymentTime, false);
		}
		// 12点前 更新昨日、当日 （不带逾期信息）
		else {
			firstRepaymentTime = dateFormat.format(now.getTime());
			reportRepayment(firstRepaymentTime, false);

			now.add(Calendar.DAY_OF_YEAR, -1);
			firstRepaymentTime = dateFormat.format(now.getTime());
			reportRepayment(firstRepaymentTime, false);
		}

	}
	
	

}